package com.my.study.pool;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

import static java.lang.Thread.sleep;

/**
 * @author Carlos
 * @version 1.0
 * @Description TODO
 * @date 2021/6/13 19:50
 **/
@Slf4j(topic = "c.TestSubmit")
public class TestSubmit {

    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(1);
//        futureSubmit(pool);
//        invokeAll(pool);
        invokeAny(pool);
    }


    private static void futureSubmit(ExecutorService pool) throws Exception {
        Future<String> future = pool.submit(() -> {
            log.debug("running");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "OK";
        });

        log.debug("结果 {}", future.get(2000, TimeUnit.MILLISECONDS));
    }

    private static void invokeAll(ExecutorService pool) throws Exception {

        List<Future<String>> invokeResult = pool.invokeAll(Arrays.asList(
                () -> {
                    log.debug("begin 1");
                    sleep(4000);
                    log.debug("end 1");
                    return "1";
                },
                () -> {
                    log.debug("begin 2");
                    sleep(5000);
                    log.debug("end 2");
                    return "2";
                },
                () -> {
                    log.debug("begin 3");
                    sleep(3000);
                    log.debug("end 3");
                    return "3";
                }
        ));

        invokeResult.forEach(f -> {
            try {
                String result = f.get();
                log.debug("结果： {}", result);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }

        });
    }

    private static void invokeAny(ExecutorService pool) throws Exception {

        String result = pool.invokeAny(Arrays.asList(
                () -> {
                    log.debug("begin 1");
                    sleep(1000);
                    log.debug("end 1");
                    return "1";
                },
                () -> {
                    log.debug("begin 2");
                    sleep(5000);
                    log.debug("end 2");
                    return "2";
                },
                () -> {
                    log.debug("begin 3");
                    sleep(3000);
                    log.debug("end 3");
                    return "3";
                }
        ));

        log.debug("结果：{}", result);
    }

}
